import NoteUser from "../../genshin/model/mys/NoteUser.js";

const arr2 =[
    { name: 'android01', alias: ['官', '安卓1', '安卓一', '国', '安卓国', '安卓官'] },  
    { name: 'bb01', alias: ['安卓2', '安卓二', 'b', 'B', 'bilibili', 'bili', '哔哩哔哩', 'b站',] },  
    { name: 'hun01', alias: ['安卓三', '安卓3', '华为', 'vivo', 'oppo', '渠道1', '渠道一', '渠道1服'] }, 
    { name: 'hun02', alias: ['小米', '360', '豌豆荚', '九游', '渠道2', '渠道二', '安卓四'] },
    { name: 'pc01', alias: ['桌面', '桌面服', '全平台', '全平台服', 'pc'] },
    { name: 'ios01', alias: ['ios', 'IOS', '苹果', 'apple', '果'] },
    { name: 'yyb01', alias: ['宝', '应用宝'] },
  ]
class BH3UserInfo {
  constructor(e) {
    this.e = e;
  }

  async user() {
    return await NoteUser.create(this.e);
  }

  async getUserInfo(inputUid = null, inputServer = null) {
    try {
     console.log(`开始处理用户请求，输入UID: ${inputUid}, 输入服务器: ${inputServer}`);
      let user1 = await this.user();
      
      if (!user1.hasCk) {
        throw new Error('当前尚未绑定cookie,请使用#扫码登录');
      }
      let mys = user1.getMysUser(this.e);
      let ck = mys.ck;
      if (!ck) {
        throw new Error('无ck');
      }
      let atUsers = this.e.message.filter(m => m.type === 'at').map(at => at.qq);
      let targetUser = atUsers.length > 0 ? atUsers[0] : this.e.user_id;

      let uid, server;
      if (inputUid && inputServer) {
        uid = inputUid;
        server = this.getServerFromAlias(inputServer);
      } else {
        uid = await redis.get(`BH3:UID:${targetUser}`);
        let serverAlias = await redis.get(`BH3:SERVER:${targetUser}`);
        server = this.getServerFromAlias(serverAlias);
      }
      if (!uid || !server) {
        throw new Error("无法获取有效的UID和服务器信息");
      }
      if (!/^\d{8,10}$/.test(uid)) {
        throw new Error(`UID 必须为8到10位数字`);
      }
      const mysuid = this.extractMysuid(ck);
      console.log(`处理完成: UID=${uid}, 服务器=${server}, MysUID=${mysuid}, 目标用户=${targetUser}`);
      console.log(ck)
      return { uid, server, mysuid,ck };
      
    } catch (error) {
      console.error("处理uid出错:", error);
      throw error;
    }
  }
  getServerFromAlias(alias) {
    if (!alias) return null;
    const foundItem = arr2.find(item => 
      item.name === alias || item.alias.includes(alias.toLowerCase())
    );
    return foundItem ? foundItem.name : null;
  }
  extractMysuid(ck) {
    const mat = ck.match(/account_id=([^;]+)/);
    return mat ? mat[1] : null;
  }
}

export {BH3UserInfo};